import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'AppNavigator.dart';
import 'NetworkManager.dart';
import 'Refresher.dart';

abstract class BaseState<T extends StatefulWidget> extends State<T>
    with NetworkCallback, WidgetsBindingObserver
    implements IRefresher {
  bool initialized = false;
  BuildContext? progressContext;
  Refresher? refresher;
  bool doNotCloseProgress =
      false; //不要关闭progress，一般的，如果一个页面需要先后发送2个请求A和B，请求A收到响应后不关闭progress，等到请求B回来后再关闭，则收到A的响应后设置为true
  bool doNotShowProgressBar =
      true; //不要显示progress，譬如说下拉刷新和上拉加载更多的时候不需要显示progress

  @override
  Widget build(BuildContext context) {
    return Text('');
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      initialized = true;
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void setState(VoidCallback fn) {
    if (this.mounted) {
      super.setState(fn);
    } else {
      print('error, set state unmounted');
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    log('didChangeAppLifecycleState');
    switch (state) {
      case AppLifecycleState.resumed:
        onResume();
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.paused:
        onPause();
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  void onResume() {
    log('onResume');
  }

  void onPause() {
    log('onPause');
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {}

  @override
  void onReqError(int code, String msg) {
    // msg = msg == null ? "数据错误" : msg;
    if (msg.isNotEmpty) {
      Toast.show(msg);
    }
  }

  @override
  onReqStart() {
    log("onStart: ${this.initialized}" );
    if (initialized) {
      if (doNotShowProgressBar == false) {
        doNotShowProgressBar = true;
        showProgress();
      }
    } else {
      WidgetsBinding.instance?.addPostFrameCallback((_) async {
        //第一帧绘制完成时的回调
        if (doNotShowProgressBar == false) {
          doNotShowProgressBar = true;
          showProgress();
        }
      });
    }
  }

  @override
  void onReqFinish() {
    log("on end");
    if (doNotCloseProgress == true) {
      doNotCloseProgress = false;
    } else {
      closeProgress();
    }
    refresher?.finish();
  }

  @override
  void onLoadMore() {}

  @override
  void onRefresh() {}

  void goBack() {
    AppNavigator.pop(context);
  }

  @override
  void finishLoadMoreWithNoMoreData() {
    Toast.show('没有更多数据了');
  }

  sendRequest(model, {path, data, method, queryParameters, isForm: false, doNotShowProgressBar: false}) {
    if (data == null) data = {};
    this.doNotShowProgressBar = doNotShowProgressBar;
    onReqStart();
    Future<Map<String, dynamic>?> future = NetworkManager().sendRequest(
        path: path, data: data, method: method, callback: this, isForm: isForm, queryParameters: queryParameters);
    future.then((value) => {
      if (value == null) {
        onReqError(-1, "网络错误"),
      } else if (value['code'] == 0) {
        if (model is BaseConvert){
          model = model.parseFromMap(value),
          print('解析成功'),
          onReqSuccess(model, value['code'], value['msg'], path)
        } else {
          log("not ok"), onReqError(value['code'], '')
        },
      } else {
        onReqError(value['code'], value['msg'])
      },
      onReqFinish()
    }).catchError((e) {
      print('数据错误 ${e}');
      onReqError(-1, '数据错误');
      onReqFinish();
    });
  }

  sendRequest2(model, {path, data, method, queryParameters, isForm: false, doNotShowProgressBar: false, NetworkCallback? callback}) {
    this.doNotShowProgressBar = doNotShowProgressBar;
    onReqStart();
    Future<Map<String, dynamic>?> future = NetworkManager().sendRequest(path: path, data: data, method: method,
        callback: this, isForm: isForm, queryParameters: queryParameters);
    future.then((value) => {
      if (value == null) {
        callback?.onReqError(-1, "网络错误"),
      } else if (value['code'] == 0) {
        if (model is BaseConvert){
          log("ok"),
          model = model.parseFromMap(value),
          callback?.onReqSuccess(model, value['code'], value['msg'], path)
        } else {
          log("not ok"), onReqError(value['code'], '')
        },
      } else {
        callback?.onReqError(value['code'], value['msg'])
      },
      callback?.onReqFinish()
    }).catchError((e) {
      print('解析错误');
      callback?.onReqError(-1, '数据错误');
      callback?.onReqFinish();
    });
  }

  void sendReq(NetworkParams api, model,
      {bool doNotShowProgressBar = false,
      Map<String, dynamic>? data,
      Map<String, dynamic>? queryParameters}) {
    return sendRequest(model,
        doNotShowProgressBar: doNotShowProgressBar,
        path: api.path,
        method: api.method,
        isForm: api.isForm,
        data: data,
        queryParameters: queryParameters);
  }

  showProgress() {
    if (progressContext != null) {
      print('dialog has been shown!!!');
      return;
    }
    showDialog(
        routeSettings: RouteSettings(name: 'progress'),
        context: context,
        builder: (BuildContext context) {
          progressContext = context;
          log("show progress。 ${progressContext}"); //dirty
          // WidgetsBinding.instance?.addPostFrameCallback((_) async { //todo 以后再优化吧
          //   closeProgress();
          // });
          return Center(
            child: CircularProgressIndicator(),
          );
        }).then((value) => {
          print(value),
          progressContext = null
        });
  }

  void closeProgress() {
    print('close progress');
    if (progressContext != null) {
      print('progress context not null');
      // Navigator.pop(progressContext); //todo Looking up a deactivated widget's ancestor is unsafe
      AppNavigator.popProgressIfExists(progressContext!);
      progressContext = null;
    }
  }

  Widget? buildEmptyPage() {
    Widget? emptyView = buildEmptyView();
    Widget? initView = buildInitView();
    if (refresher != null) {
      if (refresher!.data == null) {
        return initView == null ?  H(10) : initView;
      } else if (refresher!.data?.length == 0) {
        return emptyView == null ? Center(child: LoadImage('placeholder_no_data')) : emptyView;
      } else {
        return null;
      }
    }
    return Center(child: LoadImage('placeholder_no_data'));
  }

  Widget? buildEmptyView() {}
  Widget? buildInitView() {}
}
